package com.kd.captcha;

import com.kd.captcha.storage.ICaptchaStorage;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class CaptchaManager implements ICaptchaManager {

    public static final long DEF_TIMEOUT = 5L;

    public static final int DEF_LENGTH = 6;

    private final ICaptchaStorage captchaStorage;

    private final ICaptchaGenerator captchaGenerator;

    public CaptchaManager(ICaptchaStorage captchaStorage, ICaptchaGenerator captchaGenerator) {
        this.captchaStorage = captchaStorage;
        this.captchaGenerator = captchaGenerator;
    }

    @Override
    public Captcha generate(String name, String biz) {
        return this.generate(name, biz, DEF_TIMEOUT, DEF_LENGTH);
    }

    @Override
    public Captcha generate(String name, String biz, long timeout) {
        return this.generate(name, biz, timeout, DEF_LENGTH);
    }

    @Override
    public Captcha generate(String name, String biz, long timeout, int length) {
        String value = captchaGenerator.generate(length);
        Captcha captcha = new Captcha(name, value, biz);

        this.captchaStorage.set(captcha, timeout, TimeUnit.MINUTES);

        return captcha;
    }

    @Override
    public boolean validate(Captcha captcha) {
        Captcha cacheCaptcha = this.getCaptcha(captcha.getName(), captcha.getBiz());
        return cacheCaptcha != null && captcha.getValue().equals(cacheCaptcha.getValue());
    }

    @Override
    public boolean remove(Captcha captcha) {
        return this.captchaStorage.remove(captcha);
    }

    @Override
    public Captcha getCaptcha(String name, String biz) {
        return this.captchaStorage.get(name, biz);
    }
}
